package com.lagou.pojo;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;



// PropertySource默认取application.properties
//@PropertySource(value = "bootstrap.yml")
@Data
@Component
@ConfigurationProperties(prefix = "ip.manager")
@RefreshScope
public class IpManager {

    /*private static IpManager ipManager;

    public static IpManager getInstance(){
        synchronized (ipManager){
            if(ipManager == null){
                ipManager = new IpManager();
            }
        }
        return ipManager;
    }*/

    private long effectiveTime;
    private int maxAccessNumber;

    private List<IpMonitor> ipMonitorList = new ArrayList<>();

    public void addIpMonitor(IpMonitor ipMonitor){
        ipMonitorList.add(ipMonitor);
    }

    public boolean isAccess(String ip){
        List<IpMonitor> ipMonitors = this.ipMonitorList.stream()
                .filter(ipMonitor -> System.currentTimeMillis() - ipMonitor.getCreateTime() > effectiveTime)
                .collect(Collectors.toList());

        if(ipMonitors != null && ipMonitors.size() > 0){
            this.ipMonitorList.removeAll(ipMonitors);
        }

        long count = this.ipMonitorList.stream().filter(ipMonitor -> ipMonitor.getIp().equals(ip)).count();

        return count < maxAccessNumber;
    }

}
